import { useAuthStore } from '@/store/modules/auth';
import { useAppStore } from '@/store/modules/app';

// 请求配置接口
export interface RequestConfig {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: any;
  timeout?: number;
}

// 响应数据接口
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
  success: boolean;
}

// 基础配置
const BASE_URL = process.env.NODE_ENV === 'development' 
  ? 'http://localhost:3000/api' 
  : 'https://your-api-domain.com/api';

const DEFAULT_TIMEOUT = 10000;

// 获取Token
const getToken = (): string | null => {
  const authStore = useAuthStore();
  return authStore.token;
};

// 请求拦截器
const requestInterceptor = (config: RequestConfig): RequestConfig => {
  const token = getToken();
  
  // 设置默认请求头
  const defaultHeaders = {
    'Content-Type': 'application/json',
  };
  
  // 添加认证token
  if (token) {
    defaultHeaders['Authorization'] = `Bearer ${token}`;
  }
  
  config.header = {
    ...defaultHeaders,
    ...config.header,
  };
  
  return config;
};

// 响应拦截器
const responseInterceptor = <T>(response: any): Promise<ApiResponse<T>> => {
  return new Promise((resolve, reject) => {
    const { statusCode, data } = response;
    
    if (statusCode === 200) {
      // 成功响应
      if (data.success) {
        resolve(data);
      } else {
        // 业务错误
        uni.showToast({
          title: data.message || '请求失败',
          icon: 'none',
        });
        reject(data);
      }
    } else if (statusCode === 401) {
      // 未授权，清除token并跳转登录
      const authStore = useAuthStore();
      authStore.logout();
      uni.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none',
      });
      uni.reLaunch({
        url: '/pages/auth/login',
      });
      reject(response);
    } else {
      // 其他错误
      uni.showToast({
        title: `请求失败 (${statusCode})`,
        icon: 'none',
      });
      reject(response);
    }
  });
};

// 主要请求函数
export const request = <T = any>(config: RequestConfig): Promise<ApiResponse<T>> => {
  const appStore = useAppStore();
  
  return new Promise((resolve, reject) => {
    // 显示加载状态
    appStore.setLoading(true);
    
    // 应用请求拦截器
    const finalConfig = requestInterceptor(config);
    
    uni.request({
      url: `${BASE_URL}${finalConfig.url}`,
      method: finalConfig.method || 'GET',
      data: finalConfig.data,
      header: finalConfig.header,
      timeout: finalConfig.timeout || DEFAULT_TIMEOUT,
      success: (res) => {
        responseInterceptor<T>(res)
          .then(resolve)
          .catch(reject)
          .finally(() => {
            appStore.setLoading(false);
          });
      },
      fail: (error) => {
        appStore.setLoading(false);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none',
        });
        reject(error);
      },
    });
  });
};

// 便捷方法
export const get = <T = any>(url: string, data?: any, config?: Partial<RequestConfig>): Promise<ApiResponse<T>> => {
  return request<T>({
    url,
    method: 'GET',
    data,
    ...config,
  });
};

export const post = <T = any>(url: string, data?: any, config?: Partial<RequestConfig>): Promise<ApiResponse<T>> => {
  return request<T>({
    url,
    method: 'POST',
    data,
    ...config,
  });
};

export const put = <T = any>(url: string, data?: any, config?: Partial<RequestConfig>): Promise<ApiResponse<T>> => {
  return request<T>({
    url,
    method: 'PUT',
    data,
    ...config,
  });
};

export const del = <T = any>(url: string, data?: any, config?: Partial<RequestConfig>): Promise<ApiResponse<T>> => {
  return request<T>({
    url,
    method: 'DELETE',
    data,
    ...config,
  });
};